unit unit_FormMain;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ExtCtrls, Buttons, ComCtrls, INIFiles,LResources, DefaultTranslator, Menus,
  {$ifdef Unix}
  BaseUnix,
  {$ENDIF}
  unit_eQSLutils, unit_Utils;

type

  { TFormMain }

  TFormMain = class(TForm)
    Button1: TBitBtn;
    Button2: TBitBtn;
    Button3: TBitBtn;
    CheckBox1: TCheckBox;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    LabelMessages: TLabel;
    MainMenu1: TMainMenu;
    MenuItem1: TMenuItem;
    MenuItem2: TMenuItem;
    ProgressBar1: TProgressBar;
    SelectDirectoryDialog1: TSelectDirectoryDialog;
    txtUser: TEdit;
    txtPassword: TEdit;
    txtPath: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure CheckBox1Change(Sender: TObject);
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure MenuItem1Click(Sender: TObject);
    procedure txtPasswordChange(Sender: TObject);
    procedure txtPathChange(Sender: TObject);
    procedure txtUserChange(Sender: TObject);
    procedure CheckMyCheckBox;
    procedure Messages(MyText:String);
    function GetMyQSL:String;
    function WriteConfFile(ConfFileName:String):Boolean;
    function ReadConfFile(ConfFileName:String):Boolean;
  private
    { private declarations }

  public
    { public declarations }

  end; 

var
  FormMain: TFormMain;
  InboxFile: string;
  User:String;
  Password:String;
  Path:String;
  ConfFileName:String;
//  ConfFileOptions:Array[0..2] of String;
  QSLCount:Integer;
resourcestring
//----------------------------------------
// Labels:
Label1Msg='eQSL User:';
Label2Msg='eQSL Password:';
Label3Msg='Path to store your QSLs:';
//----------------------------------------
// CheckBox:
CheckBox1Msg='Save my data';
//
Button1Msg='Exit';
Button2Msg='Download';

HintButton1='Exit from this program';
HintButton2='Start your download';
HintButton3='Select the path where you whish save QSLs';

msg1='Please, enter your eQSL user.';
msg2='Please, enter your eQSL password.';
msg3='Please, enter a path where download your QSL cards.';
msg4='The path does not exist. Please, check it';
msg5='The path is not writable for you.';
msg6='Login to eQSL site...';
msg7='You entered an incorrect User or Password.';
msg8='Login to eQSL site...[OK]';
msg9='Generating your Inbox file...';
msg10='I cant generate your Inbox.';
msg11='Generating your Inbox file...[OK]';
msg12='Starting download QSLs...';
msg13='I cant download your Inbox.';
msg14='Starting download QSLs...';
msg15a='Starting download ';
msg15b=' QSLs...';
msg16='Download QSL from ';
msg17='I cant download ';
msg18a='QSL from ';
msg18b=' already exists. No download.';

implementation

{$R *.lfm}

{ TFormMain }

procedure TFormMain.Button2Click(Sender: TObject);
var nulo: string;

  URLInbox: String;
  attrs: Integer;
begin

  if txtUser.Text = '' then
  begin
       ShowMessage(msg1);
     txtUser.SetFocus;
     Exit
  end;

  if txtPassword.Text = '' then
  begin
     ShowMessage(msg2);
     txtPassword.SetFocus;
     Exit;
  end;

  if txtPath.Text = '' then
  begin
     ShowMessage(msg3);
     txtPath.SetFocus;
     Exit;
  end;

  If not DirectoryExists(txtPath.Text) Then
  begin
     ShowMessage(msg4);
     txtPath.SetFocus;
     Exit;
  end;

  {$ifdef Unix}
  if fpAccess (txtPath.Text,W_OK)<>0 then
    begin
    ShowMessage(msg5);
    txtPath.SetFocus;
    Exit;
    end;
  {$ENDIF}

   User:=txtUser.Text;
    Password:=txtPassword.Text;
    Path:=txtPath.Text;


Messages(msg6);

if eQSLLogin(txtUser.Text, txtPassword.Text) <> '' Then
begin
   ShowMessage(msg7);
   txtUser.SetFocus;
   Exit;
end;

Messages(msg8);


Messages(msg9);


URLInbox:=eQSLGenerateInbox;


if URLInbox = '' Then
begin
   ShowMessage(msg10);
   txtUser.SetFocus;
   Exit
end;

Messages(msg11);


// Faltaría garantizar que el directorio es escribible.
{$IFDEF Win32}
InboxFile:=ExtractFilePath(ParamStr(0)) + 'inbox.tmp';
{$ENDIF}
{$ifdef Unix}
InboxFile:=ExtractFilePath(ParamStr(0)) + '.inbox.tmp';
{$ENDIF}
// Habría que cambiarle el nombre a esta función ya que no baja
//

Messages(msg12);


if eQSLDownload(URLInbox, InboxFile) <> '' then
begin
   ShowMessage(msg13);
   txtUser.SetFocus;
   Exit
end;

Messages(msg14);


QSLCount:=eQSLCountInbox(InboxFile);

If QSLCount < 1 then
begin
   Exit;
end;

Messages(msg15a + IntToStr(QSLCount) + msg15b);

ProgressBar1.Min:=0;
ProgressBar1.Max:=QSLCount;
nulo:=GetMyQSL;

end;

procedure TFormMain.Messages(MyText:String);
begin
   LabelMessages.Caption:=MyText;
   LabelMessages.Update;
   FormMain.Update;
end;

procedure TFormMain.Button1Click(Sender: TObject);
begin
       Close;
end;

procedure TFormMain.Button3Click(Sender: TObject);
begin
  SelectDirectoryDialog1.Execute;
  txtPath.Text:=SelectDirectoryDialog1.FileName;
end;

procedure TFormMain.CheckBox1Change(Sender: TObject);
begin
  if CheckBox1.Checked then
    begin
    txtUser.Enabled:=False;
    txtPassword.Enabled:=False;
    txtPath.Enabled:=False;

    end
    else
    begin
    txtUser.Enabled:=True;
    txtPassword.Enabled:=True;
    txtPath.Enabled:=True;
    end;

end;

procedure TFormMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
var
  x:Boolean;
  ConfFileName:String;
begin
{$IFDEF Win32}
ConfFileName:=ExtractFilePath(ParamStr(0)) + 'config.ini';
{$ENDIF}
{$ifdef Unix}
ConfFileName:=ExtractFilePath(ParamStr(0)) + 'config.conf';
{$ENDIF}
  if CheckBox1.Checked then
    begin
x:=WriteConfFile(ConfFileName);
   end
  else
      If FileExists(ConfFileName) Then
        begin
      if DeleteFile(Utf8ToAnsi(ConfFileName))=False Then
        ShowMessage('Error');
        end;
end;

procedure TFormMain.FormCreate(Sender: TObject);
var
  x:Boolean;
begin

Label1.Caption:=Label1Msg;
Label2.Caption:=Label2Msg;
Label3.Caption:=Label3Msg;

Button1.Hint:=HintButton1;
Button2.Hint:=HintButton2;
Button3.Hint:=HintButton3;

CheckBox1.Caption:=CheckBox1Msg;

CheckBox1.Enabled:=False;

Button1.Caption:=Button1Msg;
Button2.Caption:=Button2Msg;

LabelMessages.Caption:='';
FormMain.Constraints.MaxHeight:=FormMain.Height;
FormMain.Constraints.MaxWidth:=FormMain.Width;

{Verifico si existe el archivo de configuración
si no existe, lo creo
si existe, lo leo
}
//  ShowMessage ('Test');
{$IFDEF Win32}
ConfFileName:=ExtractFilePath(ParamStr(0)) + 'config.ini';
{$ENDIF}
{$ifdef Unix}
ConfFileName:=ExtractFilePath(ParamStr(0)) + 'config.conf';
{$ENDIF}

If Fileexists(ConfFileName) Then
   begin

   x:=ReadConfFile(ConfFileName);
   CheckBox1.Checked:=True;
   end
   else
   begin

   end;

end;

procedure TFormMain.MenuItem1Click(Sender: TObject);
begin

end;


procedure TFormMain.txtPasswordChange(Sender: TObject);
begin
    CheckMyCheckBox;
end;

procedure TFormMain.txtPathChange(Sender: TObject);
begin
  CheckMyCheckBox;
end;

procedure TFormMain.txtUserChange(Sender: TObject);
begin
  CheckMyCheckBox;
end;
procedure TFormMain.CheckMyCheckBox;
begin
  if (txtUser.Text <> '') and (txtPassword.Text <> '') and (txtPath.Text <> '') then
    CheckBox1.Enabled:=True
  else
  CheckBox1.Enabled:=False;
end;


function TFormMain.GetMyQSL:String;
    var
      myFile:TextFile;
      myLine:String;
      i:Integer;
      Count:Integer;
      CallSign:String;
      Band:String;
      Mode:String;
      Date:String;
      Day:String;
      Month:String;
      Year:String;
      FileFormat:String;
      FileName:String;
      Time:String;
      Hour:String;
      Min:String;
      URL:String;
      A:TStringList;
      P:String;
         begin
           Count:=1;
              if eQSLUseJPG then
                  FileFormat:='jpg'
              else
                  FileFormat:='png';

           AssignFile(myFile, InboxFile);
           FileMode := fmOpenRead;
           try
           Reset(myFile);
           repeat
             Readln(myFile, myLine);
             if AnsiPos('<CALL:', myLine) = 1 then
             begin

                myLine:=StringReplace(myLine, '<', ' ',[rfReplaceAll, rfIgnoreCase]);
                myLine:=StringReplace(myLine, '>', ' ',[rfReplaceAll, rfIgnoreCase]);
                try

                A:=TStringList.Create;
                A.Delimiter := ' ';
                A.DelimitedText:=myLine;
                for i := 0 to A.Count-1 do
                    begin
                    // En los i pares tengo
                    if AnsiPos('CALL:', A[i]) <> 0 then
                    begin
                         CallSign:=A[i+1];
                    // To callsigns in portable, change / with -:
                         CallSign:=StringReplace(CallSign, '/', '-', [rfReplaceAll, rfIgnoreCase]);
                    end;

                    if AnsiPos('QSO_DATE:', A[i]) <> 0 then
                    begin
                         if IsNumeric(A[i+1])=true then
                         begin
                         Date:=A[i+1];
                         Year:=Copy(A[i+1], 1, 4);
                         Month:=Copy(A[i+1], 5, 2);
                         Day:=Copy(A[i+1], 7, 2);
                         end;

                    end;

                    if AnsiPos('TIME_ON:', A[i]) <> 0 then
                    begin
                         if IsNumeric(A[i+1])=true then
                         begin
                         Time:=A[i+1];
                         Hour:=Copy(A[i+1], 1, 2);
                         Min:=Copy(A[i+1], 3, 2);
                         end;
                    end;

                    if AnsiPos('MODE:', A[i]) <> 0 then
                    begin
                         Mode:=A[i+1];
                    end;

                    if AnsiPos('BAND:', A[i]) <> 0 then
                    begin
                         Band:=A[i+1];
                    end;
                    end;
// Acá genero el nombre:
{$IFDEF Win32}
FileName:=Path + '\';
{$ENDIF}
{$ifdef Unix}
FileName:=Path + '/';
{$ENDIF}
FileName:=FileName + '' + CallSign + '_' + Date + '_' + Time + '_' + Band + '_' + Mode + '.' + FileFormat;

Messages(msg16 + Callsign + '  (' +  IntToStr(Count) + '/' + IntToStr(QSLCount) + ')...');

ProgressBar1.StepBy(+1);
//ProgressBar1.Step:=Count;
ProgressBar1.Refresh;
Count:=Count+1;

if not FileExists(FileName) then
begin
URL:='http://www.eqsl.cc/qslcard/DisplayeQSL.cfm?Callsign=' + CallSign + '&VisitorCallsign=' + User + '&QSODate=' + Year + '-' + Month + '-' + Day + '%20' + Hour + ':' + Min + ':00.0&Band=' + Band + '&Mode=' + MODE;
if eQSLGetQSL(URL, FileName) <> true then
   begin
   ShowMessage(msg17 + URL);
end;


end
else
Messages(msg18a + Callsign + msg18b);
//end;
                finally
                  A.Free;
                end;



             end;
           until(EOF(myFile));

           finally
             CloseFile(myFile);
           end;


         end;
function TFormMain.WriteConfFile(ConfFileName:String):Boolean;
var
  MyFile:TIniFile;
         begin
         MyFile:= TIniFile.Create(ConfFileName);
         try

      MyFile.WriteString('eQSL_User', 'User', txtUser.Text);
      MyFile.WriteString('eQSL_User', 'Password', txtPassword.Text);
      MyFile.WriteString('Preferences', 'Path', txtPath.Text);

      result:=True;
         finally
           MyFile.Free;
         end;
         end;
function TFormMain.ReadConfFile(ConfFileName:String):Boolean;
var
  MyFile:TIniFile;
  x:String;
  begin
       MyFile:= TIniFile.Create(ConfFileName);
       try

       txtUser.Text:=MyFile.ReadString('eQSL_User', 'User', '');
       txtPassword.Text:=MyFile.ReadString('eQSL_User', 'Password', '');
       txtPath.Text:=MyFile.ReadString('Preferences', 'Path', '');

       result:=True;
     finally
       MyFile.Free;
  end;
end;
end.


